import { getList } from '@/api/article';
import { ApiCode, BaseApi, BaseList } from '@/types/api/base';

interface DataType {
    list: any[]
    [key: string]: any
}
type Service<ServiceReturnParam, ServiceReturn> = (args: ServiceReturnParam) => Promise<BaseApi<ServiceReturn & DataType>>;

type GetDefaultListType<R> = R extends BaseList<(infer U)> ? U : never;
type Opt<Param, List> = {
    /**默认传参 */
    defaultParam: Param
    /**默认列表 */
    defaultList?: GetDefaultListType<List>[]
    /**默认第几页 */
    defaultPage?: number
    /**默认每页数量 */
    defaultLimit?: number
    /**请求完成后 */
    success?: () => void
};



const useList = <ServiceReturnParam, ServiceReturn>(service: Service<ServiceReturnParam, ServiceReturn>, opt: Opt<ServiceReturnParam, ServiceReturn>) => {
    const state = reactive({
        isloading: false,
        list: opt.defaultList ?? [],
        total: 0,
        page: opt.defaultPage ?? 1,
        limit: opt.defaultLimit ?? 10,
    })

    /**执行请求 */
    const run = async () => {
        state.isloading = true
        const res = await service(opt.defaultParam)
        if (res.code === ApiCode.success) {
            state.page += 1
            state.list.concat(res.data.list)
        }
        state.isloading = false
    }

    return {
        run,
        isloading: toRef(state, 'isloading'),
    }
}

useList(getList, {
    defaultParam: {},
    defaultList: [],
})
export { useList } 